package com.turing.model.registry.schedule;

import com.turing.common.util.Tools;
import com.turing.model.registry.model.domain.RegisterInstance;
import com.turing.model.registry.service.RegisterInstanceService;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class HeartBeatScheduleService {

    @Autowired
    private RegisterInstanceService registerInstanceService;

    private Log logger = LogFactory.getLog(HeartBeatScheduleService.class);

    @XxlJob(value="healthCheck")
    @Transactional(propagation = Propagation.REQUIRED)
    public void healthCheck(){

        List<RegisterInstance> expiredInstances = registerInstanceService.getExpiredInstances();
        if(Tools.isNotEmpty(expiredInstances)){
            logger.info(expiredInstances);
            expiredInstances.forEach(ei->{
                String host = ei.getHost();
                String port = ei.getPort();
                String appType = ei.getAppType();
                String cardNo = ei.getCardNo();
                // remove job
                registerInstanceService.stopAndRemoveJob(host, port, appType, cardNo);
                // remove instance not exist
                logger.info(ei.getId());
                registerInstanceService.removeById(ei.getId());

            });
        }

    }

}
